package com.myblog.controller;

import com.myblog.pojo.UserMessage;
import com.myblog.pojo.Wechat;
import com.myblog.service.Usermessageservice;
import com.myblog.utils.JsonData;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Source;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class Messagecontroller {

    @RequestMapping("/message")
    public Object message(HttpServletRequest request, Model model){
        HttpSession session=request.getSession();
        Wechat wechat=(Wechat)session.getAttribute("wechat");
        if(wechat!=null){
            System.out.println(wechat);
//            model.addAttribute("wxname",wechat.getWxname().toString());
            model.addAttribute("wximage", URLDecoder.decode(wechat.getImageurl().toString()));
            model.addAttribute("wxname",wechat.getWxname());
        }
        return "message";
    }

    @Autowired
    private Usermessageservice usermessageservice;

    @RequestMapping("/findmessage")
    @ResponseBody
    public Object findmessage(){
        List<UserMessage> userMessages=usermessageservice.findwechat();
        for(UserMessage userMessage:userMessages){
            Wechat pwechat=userMessage.getPwechat();
            pwechat.setImageurl(URLDecoder.decode(pwechat.getImageurl().toString()));
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            String str=sdf.format(userMessage.getTime());
            userMessage.setDate(str);
        }
        return JsonData.buildSuccess(userMessages);
    }

    @RequestMapping("/content")
    @ResponseBody
    public Object content(@Param("content") String content,HttpServletRequest request){
//        System.out.println(content);
        HttpSession session=request.getSession();
        if(session!=null){
            Wechat wechat=(Wechat)session.getAttribute("wechat");
//            System.out.println(wechat);
//            System.out.println(new SimpleDateFormat().format(new Date()));
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            ;
            usermessageservice.insert(wechat.getOpenId().toString(),content,sdf.format(new Date()));
        }
        return JsonData.buildSuccess();
    }

}
